package router

import (
	"context"
	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/app/server"
	"github.com/cloudwego/hertz/pkg/common/config"
	"github.com/cloudwego/hertz/pkg/common/hlog"
	"github.com/hertz-contrib/jwt"
	"net/http"
	hello2 "primus/consumer-service/handler/hello"
	"primus/consumer-service/model/auth"
	"primus/consumer-service/service/auth/auth_service"
	"primus/pkg/constants"
	"primus/pkg/mw"
	"time"
)

func Init(r *server.Hertz) {
	authMiddleware, _ := jwt.New(&jwt.HertzJWTMiddleware{
		Key:        []byte(constants.SecretKey),
		Timeout:    time.Hour,
		MaxRefresh: time.Hour,
		PayloadFunc: func(data interface{}) jwt.MapClaims {
			if v, ok := data.(int64); ok {
				return jwt.MapClaims{
					constants.IdentityKey: v,
				}
			}
			return jwt.MapClaims{}
		},
		LoginResponse: func(ctx context.Context, c *app.RequestContext, code int, token string, expire time.Time) {
			c.JSON(http.StatusOK, auth.Response{
				Msg: &auth.Msg{
					Code: 0,
					Msg:  expire.Format(constants.TIME_LAYOUT),
				},
				Data: token,
			})
		},
		Authenticator: func(ctx context.Context, c *app.RequestContext) (interface{}, error) {
			//验证入参、登录
			//var loginVar handler.UserParam
			//if err := c.Bind(&loginVar); err != nil {
			//	return "", jwt.ErrMissingLoginValues
			//}
			//
			//if len(loginVar.UserName) == 0 || len(loginVar.PassWord) == 0 {
			//	return "", jwt.ErrMissingLoginValues
			//}
			//
			//return rpc.CheckUser(context.Background(), &userdemo.CheckUserRequest{UserName: loginVar.UserName, Password: loginVar.PassWord})
			// TODO 调用第三方进行登录认证 or 自己开发登录功能
			//singleton.Json4Post()
			_, rawResp, err := auth_service.Auth(
				ctx,
				&auth.ReqBody{
					Username: "admin",
					Password: "87e7549e27550c78727f3dc3254c75fd4c015a50ead310895c914bb26f98c8d7368577d66ab49976f763c8d5a6f40966681901830bfd256e9aa8620e1bbd1e8a",
				},
				// 在发起调用的时候可指定请求级别的配置
				config.WithSD(true),                           // 指定请求级别的设置，用来开启服务发现
				config.WithReadTimeout(1000*time.Millisecond), // 指定请求读超时
			)
			return string(rawResp.Body()), err
		},
		Authorizator: func(data interface{}, ctx context.Context, c *app.RequestContext) bool {
			/*if v, ok := data.(*User); ok && v.UserName == "admin" {
				return true
			}*/
			//hlog.Info("data: ", data)

			return true
		},
		Unauthorized: func(ctx context.Context, c *app.RequestContext, code int, message string) {
			c.JSON(code, map[string]interface{}{
				"code":    code,
				"message": message,
			})
		},
		TokenLookup:   "header: Authorization, query: token, cookie: jwt",
		TokenHeadName: "Bearer",
		TimeFunc:      time.Now,
	})

	//生成License
	//r.POST("/v1/createLicence", handler.CreateLicence)
	//判断软件授权状态
	//r.GET("/v1/checkLicence", handler.CheckLicence)

	v := r.Group("/v1") //, license.LicenceIssued() ...)
	//curl -X POST "http://localhost:10000/v1/login"
	v.POST("/login", authMiddleware.LoginHandler)
	//v.POST("/register", handler.Register)

	r.NoRoute(authMiddleware.MiddlewareFunc(), func(ctx context.Context, c *app.RequestContext) {
		claims := jwt.ExtractClaims(ctx, c)
		hlog.Info("NoRoute claims: ", claims)
		c.JSON(404, map[string]string{"code": "PAGE_NOT_FOUND", "message": "Page not found"})
	})

	v1 := r.Group("/api/v1") //, license.LicenceIssued()...)

	hello := v1.Group("/hello")
	hello.Use(mw.AuthMiddleWare())
	//hello.Use(authMiddleware.MiddlewareFunc())
	{
		//curl -i -H "Accept: application/json" -H "Authorization:bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2ODI2ODc0NzQsIm9yaWdfaWF0IjoxNjgyNjgzODc0fQ.GO5JL1poD-jwKpJaBCtSHutxQEw_2UpfrNCF_b39aA0" -X GET 'http://localhost:10000/api/v1/hello'
		hello.GET("", hello2.GetH2)
	}

}
